/*
 * Copyright 2020 lcnap
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pers.lcnap.exam;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BenchmarkUtil {

    static int[] loops = new int[]{10, 100, 1000, 1_0000, 5_0000, 10_0000, 20_0000};

    public interface Invoke {
        boolean run(int i);
    }

    public static String run(Invoke invoke) {
        StringBuilder stringBuilder = new StringBuilder().append("\n");
        END:
        for (int loop : loops) {
            long start = System.currentTimeMillis();
            for (int i = 0; i < loop; i++) {
                if (!invoke.run(i)) {
                    break END;
                }
            }
            long total = System.currentTimeMillis() - start;

            String loopResult =
                    String.format("total: %15d | avg: %15f | loop: %15d | qps: %15f\n", total, (double) total / loop, loop, (loop / (double) total * 1000));
            stringBuilder.append(loopResult);
        }
        //logger.info(stringBuilder.toString());
        return stringBuilder.toString();
    }

    public static String concurrentRun(Invoke invoke, int threadNum) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(threadNum);
        CountDownLatch latch = new CountDownLatch(threadNum);
        StringBuffer builder = new StringBuffer();
        for (int k = 0; k < threadNum; k++) {
            executor.submit(() -> {
                int id = (int) Thread.currentThread().getId();
                String run = BenchmarkUtil.run(invoke::run);
                builder.append(id).append(run);
                latch.countDown();
            });
        }
        latch.await();
        return builder.toString();
    }
}
